using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeFrame : MonoBehaviour
{
    public RectTransform FrameTrm;
    public RectTransform FrameInfosContentTrm;
    public Text FrameTextTrm;
    public Vector2 FrameTextPos { get; set; }

    public RectTransform TimeCursorTrm;
    public Image SkillTimeImage;
    // Start is called before the first frame update
    void Start()
    {
        FrameTextPos = FrameTextTrm.GetComponent<RectTransform>().anchoredPosition;
        Debug.Log(FrameTextPos);
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.F1))
        {
            float time = UnityEngine.Random.Range(3, 10);
            RefreshTimeLine(time);
            // DeleteTimeLine();
        }
    }

    void RefreshTimeLine(float time)
    {
        DeleteTimeLine();
        var frameCount = (int)(time * 100);
        for (int i = 0; i < frameCount; i++)
        {
            var frameObj = GameObject.Instantiate(FrameTrm.gameObject, FrameInfosContentTrm);
            if (i % 5 != 0)
            {
                var c = frameObj.GetComponent<Image>().color;
                frameObj.GetComponent<Image>().color = new Color(c.r, c.g, c.b, .5f);
                var r = frameObj.GetComponent<RectTransform>();
                r.sizeDelta = new Vector2(r.sizeDelta.x, r.sizeDelta.y * 0.4f);
            }
            else
            {
                if (i % 10 != 0)
                {
                    var c = frameObj.GetComponent<Image>().color;
                    var r = frameObj.GetComponent<RectTransform>();
                    r.sizeDelta = new Vector2(r.sizeDelta.x, r.sizeDelta.y * 0.8f);
                }
                else
                {
                    var textObj = GameObject.Instantiate(FrameTextTrm, frameObj.transform);
                    textObj.GetComponent<RectTransform>().anchoredPosition = FrameTextPos;
                    var milis = i * 10;
                    var secs = milis / 1000;
                    var secs2 = milis % 1000 / 10;
                    textObj.GetComponent<Text>().text = $"{secs}:{secs2.ToString().PadLeft(2, '0')}";
                }
            }
		}
    }

    public void DeleteTimeLine()
    {
        //get all children
        var children = new List<GameObject>();
        foreach (Transform child in FrameInfosContentTrm)
        {
            children.Add(child.gameObject);
        }
        //destroy them
        children.ForEach(child => DestroyImmediate(child));
    }
}
